<?php 
include_once "notesrack.php";

# I don't want to land on write.php rightaway..
# They should come via notes.php coz new note 
# input form is a popup, which doesn't work decently
# without the style, as one reason. there are more reasons, though.


if ( ! isset($_SERVER['HTTP_REFERER']) ) {
	header( sprintf("Location:%s", get_url_to("notes.php")) );
	exit;
}

# To write a note, user should be logged in.
# if not, redirect to login form.

if ( logged_in() ) {
	
	if ( ! isset($_SESSION) ) {
		session_start();
		$_SESSION['note_author'] = logged_in_as();
	}

	if ( empty( $_GET ) ) {
		get_header("Write note", "Write a new note.");
		create_note_form();		
		get_footer();
	}

	if ( !empty($_POST) and isset($_GET['action']) and $_GET['action'] == "write" ) {
		$response = array (
					"errors"	=>	"",
					"success"	=>	"",					
				);
				
		if ( empty ( $_POST['note_title'] ) ) {
			$response["errors"] .= "<div>Note title has to be set. </div>";
		}
		
		
		if ( empty ( $_POST['content'] ) ) {
			$response["errors"] .= "<div>Note description has to be set.</div>";
		}		
		
		if ( $response["errors"] != "" ) {
			die ( json_encode( $response ) );
		}
		
		$note_title = htmlspecialchars( $_POST['note_title'], ENT_QUOTES ) ;		
		$note_content = $_POST['content'];
		
		$note_tags = ( empty ($_POST['note_tags']) ) ?  "" : $_POST['note_tags'];
		$note_privacy = ( empty ($_POST['note_privacy']) ) ?  "public" : "private";
		$note_author = $_SESSION['user_id'];
		
		try {
			$pdo = open_connection_pdo();	
			$stmnt = $pdo->prepare("INSERT INTO NOTES(note_title, note_content, note_author, note_privacy, note_tags) VALUES(:note_title, :note_content, :note_author, :note_privacy, :note_tags)");
			
			$stmnt->bindParam(":note_title", $note_title);
			$stmnt->bindParam(":note_content", $note_content);
			$stmnt->bindParam(":note_author", $note_author);
			$stmnt->bindParam(":note_privacy", $note_privacy);
			$note_tags = preg_replace('/\s+,\s+/' , ',', $note_tags); # replace <comma><space> with just a <comma>
			$stmnt->bindParam(":note_tags", $note_tags);
		
			$result = $stmnt->execute();
			$note_id = $pdo->lastInsertId();
		} catch( PDOException $e ) {
			$response["errors"] .= "Internal Error: Could not save the note to database.";
		}
		
		if ( $response["errors"] != "" ) {
			$pdo = null;
			die( json_encode($response) );
		}
		
		$protocol = access_protocol(); # http or https
		$response['redirect_to'] = get_url_to("notes.php");
		$response['success'] = "success";
		$response["note_id"] = "note-" . $note_id = $pdo->lastInsertId();
		echo json_encode($response);
		$pdo = null;
	}
} else { #ie. force login.
?>
<div id="user_authentication">
</div>
<div id="user_registration">
</div>
<?php	
} # Close of force login
	
?>